package stud.mpgame.physics;

/**
 * ...
 * @author pavel[f.pavel91@gmail.com]
 */
public class AABB implements IBody {

	private int left;
	private int right;
	private int bottom;
	private int top;
	
	private int nearest;
	private int nearestX;
	private int nearestY;
	
	public AABB(int left, int bottom, int right, int top) {
		this.left = left;
		this.bottom = bottom;
		this.right = right;
		this.top = top;
	}
	
	public void intersect(Circle circle) {
		//projection x
		//AABB_left = left
		//ABBB_right = rigth
		float circleLeft = circle.x - circle.radius;
		float circleRight = circle.x + circle.radius;
		float x = getMinimalVectorCoordinate(left, right, circleLeft, circleRight);
		if (x == 0)
			return;
		nearestX = nearest;	
		Vector2D vectorX = new Vector2D(x, 0);
		//projection y
		//AABB_bottom = bottom
		//AABB_top = top
		float circleBottom = circle.y - circle.radius;
		float circleTop = circle.y + circle.radius;
		float y = getMinimalVectorCoordinate(top, bottom, circleBottom, circleTop);
		if (y == 0)
			return;
		nearestY = nearest;
		Vector2D vectorY = new Vector2D(0, y);
		//temp
		if (Math.abs(x) < Math.abs(y)) { 
			circle.move(vectorX);
		} else {
			circle.move(vectorY);
            circle.velocity.y = 0;
		}
		//trace("INTERSECT");
		//Voronov projection TODO 
		//var dx = circle.x - 
	}
	
	//todo inline?
	private /*inline*/ float getMinimalVectorCoordinate(float left, float right, float bodyLeft, float bodyRight) {
		if (bodyLeft >= right || bodyRight <= left)
			return 0;
		int righti = (int) right;
		int lefti = (int) left;
		if (bodyRight > right) {
			nearest = righti;
			return right - bodyLeft;
		} else if (bodyLeft < left) {
			nearest = lefti;
			return  left - bodyRight;
		} else if (right - bodyRight < bodyLeft - left) {
			nearest = righti;
			return right - bodyLeft;
		} else {
			nearest = lefti;
			return left - bodyRight;
		}		
	}
	
}